<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\JsonResponse;

class SuccessMiddleware
{
    protected $except = [
        // ...
        'api/wechat',
    ];
    
    protected function inExceptArray($request)
    {
        foreach ($this->except as $except) {
            if ($except !== '/') {
                $except = trim($except, '/');
            }

            if ($request->fullUrlIs($except) || $request->is($except)) {
                return true;
            }
        }

        return false;
    }
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        
        if($this->inExceptArray($request)) {
            return $response;
        }

        // 执行动作
        if ($response instanceof JsonResponse) {
            
            $status = $response->getStatusCode();
            $code = $status !== 200 ? -1 : 0;
            
            $oriData = $response->getData();

            $message = [
                'code'   => $code,
                'status' => $status,
                'message' => '',
            ];

            $oriData = (array)$oriData;
            $tempData = array_get($oriData, 'data');
            $data = [];

            if(!$tempData||is_array($tempData)||(!is_array($tempData)&&!is_object($tempData))) {
                array_set($data, 'data', $tempData);
            }else{
                $data = $tempData;
            }
            
            $errcode = array_get($oriData, 'errcode');
            $errmsg = array_get($oriData, 'errmsg');
             
            $result = array_except($oriData, ['data', 'errcode', 'errmsg']);
            
            if($errcode>0){
                array_set($result, 'message', $errmsg);
                array_set($result, 'code', $errcode);
            }

            // var_dump($result);
            //print_r($data);
            $temp = ($oriData) ? array_merge($message, (array)$data, (array)$result) : $message;

            $response = $response->setData($temp);

        }else{
            $status = $response->getStatusCode();
            $code = $status !== 200 ? -1 : 0;
            $response = $response->setContent([
                'code'   => $code,
                'status' => $status,
                'message' => $response->getContent(),
            ]);
        }

        return $response;
    
    }
}
